package com.dinghui.pay.controller.wxpay;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.dinghui.pay.common.ResponseResult;
import com.dinghui.pay.pojo.TbOrder;
import com.dinghui.pay.pojo.TbUser;
import com.dinghui.pay.pojo.param.ScanCodePayOrderParam;
import com.dinghui.pay.service.OrderService;
import com.dinghui.pay.service.UserService;
import com.dinghui.pay.utils.JwtUtils;
import com.github.wxpay.sdk.MyWxPayConfig;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @author: trt
 * @description:
 * @create: 2021-06-05 19:46
 */
// 微信付款码 业务接口
@RestController
@RequestMapping("/api/wx/scanCode")
public class ScanCodeController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private OrderService orderService;

    @Value("${wxpay.app-id}")
    private String appId;

    @Value("${wxpay.app-secret}")
    private String appSecret;

    @Value("${wxpay.key}")
    private String key;

    @Value("${wxpay.mch-id}")
    private String mchId;

    @Autowired
    private MyWxPayConfig myWXPayConfig;

    /**
     * 提交扣款请求需要上传的参数
     * appid:公众号id
     * mch_id:商户号
     * nonce_str:随机字符串
     * sign:数字签名
     * body:商品描述
     * out_trade_no:商品订单号
     * total_fee:订单金额
     * spbill_create_ip:终端IP
     * auth_code:付款码
     */

    /**
     * ScanCode付款
     * 支付宝付款码的规则：
     * 支付宝付款码必须是25-30开头的数字，一共16到24位数字组成 正则：^(25|26|27|28|29|30)[0-9]{14,22}$
     * 微信付款码必须是10-15开头的数字，一共18位数字组成 正则：^1[0-5][0-9]{16}$
     */
    @PostMapping("/scanCodePayOrder")
    public ResponseResult scanCodePayOrder(@RequestBody ScanCodePayOrderParam param, @RequestHeader HashMap header) {
        String token = header.get("token").toString();
        Long userId = Long.parseLong(jwtUtils.getClaimByToken(token).getSubject());
        int orderId = param.getOrderId();
        TbUser user = new TbUser();
        user.setUserId(userId);
        long count = userService.getCount(user);
        //判断用户是否存在
        if (count == 0) {
            return ResponseResult.error("用户不存在");
        }

        //判断用户是否拥有这个订单，并且订单是未支付状态
        TbOrder order = new TbOrder();
        order.setUserId(userId.intValue());
        order.setId(orderId);
        order.setStatus(1);
        count = orderService.getCount(order);
        if (count == 0) {
            return ResponseResult.error("不是有效的订单");
        }

        // todo 验证购物券是否有效
        // todo 验证团购活动是否有效

        //查询订单详情信息
        order = new TbOrder();
        order.setId(orderId);
        order = orderService.getOne(order); //订单对象
        //向微信平台发出请求，创建支付订单
        String amount = order.getAmount().multiply(new BigDecimal("100")).intValue() + "";

        try {
            WXPay wxPay = new WXPay(myWXPayConfig);
            HashMap map = new HashMap();
            map.put("appid",appId);
            map.put("mch_id",mchId);
            map.put("nonce_str", WXPayUtil.generateNonceStr()); //随机字符串
            map.put("body", "订单备注");
            map.put("out_trade_no", order.getCode());
            map.put("total_fee", amount);
            map.put("spbill_create_ip", "127.0.0.1");
            map.put("auth_code",param.getAuthCode());
            String sign=WXPayUtil.generateSignature(map,key);
            map.put("sign",sign);
            Map<String, String> result = wxPay.microPay(map);
            String returnCode = result.get("return_code");
            String resultCode = result.get("result_code");
            if ("SUCCESS".equals(returnCode) && "SUCCESS".equals(resultCode)) {
                //更新本地商品订单信息，但是不更新商品订单状态
                String prepayId = result.get("transaction_id");
                order.setPrepayId(prepayId);
                order.setStatus(2);
                order.setPaymentType(1); //支付类型
                order.setId(order.getId());  // 查询条件
                orderService.update(order);
                return ResponseResult.success("付款成功");
            } else {
                return ResponseResult.error("付款失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("支付宝支付模块故障");
        }
    }



}